# Copyright (c) Facebook, Inc. and its affiliates.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

# Configuration file for a jupyter-notebook.
# Put this script into ~/.jupyter/ in order to get the post_save_hook implemented below.
# If you already have one, merge the content.

import os
from subprocess import check_call

def post_save(model, os_path, contents_manager):
    """post-save hook for converting notebooks to .py scripts"""
    if model['type'] != 'notebook':
        return  # only do this for notebooks

    notebook_dir, notebook_file_name = os.path.split(os_path)
    check_call(
        ['jupyter', 'nbconvert', '--to', 'script', notebook_file_name],
        cwd=notebook_dir,
    )
    py_name = os.path.splitext(notebook_file_name)[0] + ".py"
    full_py_name = os.path.join(notebook_dir, py_name)

    # Create py_gen/ dir if it doesn't exist and move the file there
    new_dir = os.path.join(notebook_dir, 'py_gen')
    if not os.path.exists(new_dir):
        os.makedirs(new_dir)
    new_py_location = os.path.join(new_dir, py_name)
    os.rename(full_py_name, new_py_location)
    full_py_name = new_py_location

    with open(full_py_name, 'r') as f:
        data = f.read()
    lines = data.split('\n')
    good_lines = []
    for line in lines:
        if ("get_ipython().magic" not in line
                and "get_ipython().run_line_magic" not in line):
            good_lines.append(line)
    # Update the file with do not edit preamble
    with open(full_py_name, 'w') as f:
        f.write("#########################################################\n")
        f.write("#\n")
        f.write("# DO NOT EDIT THIS FILE. IT IS GENERATED AUTOMATICALLY. #\n")
        f.write("# PLEASE LOOK INTO THE README FOR MORE INFORMATION.     #\n")
        f.write("#\n")
        f.write("#########################################################\n")
        f.write("\n")

        for line in good_lines:
            f.write(line + '\n')


c.FileContentsManager.post_save_hook = post_save
